// Chrome API相关的Composable
import { ref, onMounted, onUnmounted } from 'vue';
import type {
  TabInfo,
  ChromeMessage,
  MessageType,
  ExtensionSettings
} from '../../shared/types';

export function useChrome() {
  const currentTab = ref<TabInfo | null>(null);
  const tabsCount = ref(0);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // 获取当前标签页信息
  const getCurrentTab = async (): Promise<TabInfo | null> => {
    try {
      isLoading.value = true;
      error.value = null;

      const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
      });

      if (tab) {
        const tabInfo: TabInfo = {
          id: tab.id || 0,
          title: tab.title || 'Untitled',
          url: tab.url || '',
          favicon: tab.favIconUrl,
          active: tab.active,
          windowId: tab.windowId,
          index: tab.index,
          status: tab.status as 'loading' | 'complete'
        };

        currentTab.value = tabInfo;
        return tabInfo;
      }

      return null;
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to get current tab';
      console.error('Error getting current tab:', err);
      return null;
    } finally {
      isLoading.value = false;
    }
  };

  // 获取所有标签页数量
  const getTabsCount = async (): Promise<number> => {
    try {
      const tabs = await chrome.tabs.query({});
      const count = tabs.length;
      tabsCount.value = count;
      return count;
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to get tabs count';
      console.error('Error getting tabs count:', err);
      return 0;
    }
  };

  // 发送消息到background script
  const sendMessage = async <T extends MessageType>(
    action: T,
    data?: any
  ): Promise<any> => {
    try {
      const message: ChromeMessage<T> = {
        action,
        data,
        timestamp: Date.now()
      };

      return await chrome.runtime.sendMessage(message);
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to send message';
      console.error('Error sending message:', err);
      throw err;
    }
  };

  // 发送消息到content script
  const sendMessageToTab = async <T extends MessageType>(
    tabId: number,
    action: T,
    data?: any
  ): Promise<any> => {
    try {
      const message: ChromeMessage<T> = {
        action,
        data,
        timestamp: Date.now()
      };

      return await chrome.tabs.sendMessage(tabId, message);
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to send message to tab';
      console.error('Error sending message to tab:', err);
      throw err;
    }
  };

  // 存储数据到Chrome storage
  const setStorage = async <K extends keyof chrome.storage.StorageArea>(
    key: K,
    value: any
  ): Promise<void> => {
    try {
      await chrome.storage.local.set({ [key]: value });
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to set storage';
      console.error('Error setting storage:', err);
      throw err;
    }
  };

  // 从Chrome storage获取数据
  const getStorage = async <T = any>(key: string): Promise<T | null> => {
    try {
      const result = await chrome.storage.local.get(key);
      return result[key] || null;
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to get storage';
      console.error('Error getting storage:', err);
      return null;
    }
  };

  // 打开侧边栏
  const openSidePanel = async (tabId?: number): Promise<void> => {
    try {
      if (tabId) {
        await chrome.sidePanel.open({ tabId });
      } else {
        await chrome.sidePanel.open({ windowId: chrome.windows.WINDOW_ID_CURRENT });
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to open side panel';
      console.error('Error opening side panel:', err);
      throw err;
    }
  };

  // 关闭侧边栏
  const closeSidePanel = async (): Promise<void> => {
    try {
      // 方法1: 发送消息到background script
      const response = await sendMessage('CLOSE_SIDE_PANEL');

      if (response?.success) {
        console.log('Side panel close request sent successfully');
        return;
      }

      // 方法2: 直接尝试操作窗口
      if (window.close) {
        window.close();
        return;
      }

      // 方法3: 发送更新状态消息到content script
      if (currentTab.value?.id) {
        await sendMessageToTab(currentTab.value.id, 'UPDATE_SIDE_PANEL_STATE', {
          isOpen: false
        });
      }

    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to close side panel';
      console.error('Error closing side panel:', err);

      // 最后的备用方法：直接尝试关闭窗口
      try {
        if (window.close) {
          window.close();
        }
      } catch (fallbackError) {
        console.error('All close methods failed:', fallbackError);
      }
    }
  };

  // 监听标签页更新
  const onTabUpdated = (callback: (tabInfo: TabInfo) => void) => {
    const handleTabUpdate = (tabId: number, changeInfo: chrome.tabs.TabChangeInfo, tab: chrome.tabs.Tab) => {
      if (changeInfo.status === 'complete' && tab.active) {
        const tabInfo: TabInfo = {
          id: tab.id || 0,
          title: tab.title || 'Untitled',
          url: tab.url || '',
          favicon: tab.favIconUrl,
          active: tab.active,
          windowId: tab.windowId,
          index: tab.index,
          status: tab.status as 'loading' | 'complete'
        };

        callback(tabInfo);
        currentTab.value = tabInfo;
      }
    };

    chrome.tabs.onUpdated.addListener(handleTabUpdate);

    return () => {
      chrome.tabs.onUpdated.removeListener(handleTabUpdate);
    };
  };

  // 初始化
  onMounted(async () => {
    await getCurrentTab();
    await getTabsCount();

    // 监听内部关闭消息
    const handleInternalMessage = (message: any, sender: any, sendResponse: any) => {
      if (message.action === 'INTERNAL_CLOSE_SIDE_PANEL') {
        console.log('Received internal close message');
        // 尝试关闭窗口
        if (window.close) {
          window.close();
        }
        sendResponse({ success: true });
      }
    };

    chrome.runtime.onMessage.addListener(handleInternalMessage);

    // 清理函数
    onUnmounted(() => {
      chrome.runtime.onMessage.removeListener(handleInternalMessage);
    });
  });

  return {
    // 响应式数据
    currentTab,
    tabsCount,
    isLoading,
    error,

    // 方法
    getCurrentTab,
    getTabsCount,
    sendMessage,
    sendMessageToTab,
    setStorage,
    getStorage,
    openSidePanel,
    closeSidePanel,
    onTabUpdated
  };
}